<template>
  <div style='margin-left: 10px;'>
    <div style='margin-top: 20px; margin-bottom: 20px;height: 50px;'>
      <span style='margin-right: 20px;font-family: "黑体", sans-serif;font-size: 1.5em'>训练数据集</span>
      <el-button type='success' @click='fetchTableData' style='margin-left: 20px;'>搜索</el-button>
    </div>

    <el-table style='width: 96%; margin-top: 20px;' border size='small'
              :data='tableData'
              :default-sort="{prop:'date', order:'descending'}">
      <el-table-column prop='instruction' label='背景' align='left' min-width='30%' show-overflow-tooltip></el-table-column>
      <el-table-column prop='input' label='提问' align='left' min-width='30%'></el-table-column>
      <el-table-column prop='output' label='回答' align='left' min-width='60%' show-overflow-tooltip></el-table-column>
      <el-table-column prop='update_time' label='上次修改时间' align='left' min-width='20%'></el-table-column>
      <el-table-column prop='update_username' label='修改人' align='left' min-width='10%'></el-table-column>
      <el-table-column label='操作' align='center' min-width='10%'>
        <template #default='scope'>
          <el-icon class='del-btn' @click='delObj(scope.row.id)'>
            <Delete color='#f56c6c' />
          </el-icon>
          <el-icon class='upd-btn' @click.stop='editObj(scope.row)'>
            <Edit color='#FFFFFF' />
          </el-icon>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页栏 -->
    <el-pagination
      style='margin-top: 20px;'
      background
      layout='total, sizes, prev, pager, next, jumper'
      :current-page='currentPage'
      :page-sizes='[1, 2, 5, 10]'
      :page-size='pageSize'
      :total='total'
      @size-change='handleSizeChange'
      @current-change='handleCurrentChange'>
    </el-pagination>
  </div>
  <el-dialog v-model='dialogFormVisible' title='修改回答' width='50%' draggable overflow >
    <label>背景：</label>
    <br /><br />
    <el-input v-model='currentEditObj.instruction' :autosize='{minRows:2, maxRows:10}' type='textarea'></el-input>
    <br /><br />
    <label>提问：</label>
    <br /><br />
    <el-input v-model='currentEditObj.input' :autosize='{minRows:2, maxRows:4}' type='textarea'></el-input>
    <br /><br />
    <div class='output-label'>
      <label class='label-left'>回答：</label><label class='label-right'>当前文本格式：{{ currentWordType }}</label>
    </div>
    <br />
    <el-input v-model='currentEditObj.output' :autosize='{minRows:2, maxRows:10}' type='textarea'></el-input>
    <div v-if='currentWordType==="json"'>
      <span :style='{color: jsonValidateStatus === 200 ? "green":"red"}'>{{ jsonErrorInfo }}</span>
    </div>
    <div v-else>
    </div>
    <br /><br />
    <div class='dialog-foot'>
      <el-radio-group v-model='currentWordType' class='dialog-foot-radio'>
        <el-radio value='txt'>普通文本</el-radio>
        <el-radio value='json'>JSON</el-radio>
      </el-radio-group>
      <el-button type='danger' @click='dialogFormVisible=false' class='dialog-foot-button'>返回</el-button>
      <el-button type='success' @click='saveObj(currentEditObj)' class='dialog-foot-button'>保存</el-button>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref } from 'vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import { queryTrain, editTrain, validateJsonStr, deleteTrainDataset } from '/src/api'
import { useUserStore } from '/src/stores/user'

const useUser = useUserStore()
const currentPage = ref(1)
const pageSize = ref(10)
const tableData = ref([])
const total = ref(0)
const dialogFormVisible = ref(false)
const currentEditObj = ref({})
const currentWordType = ref('txt')
const jsonErrorInfo = ref('')
const jsonValidateStatus = ref(200)

const fetchTableData = () => {
  let params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }
  queryTrain(params).then((resp) => {
    tableData.value = resp.data.data.records // 假设后端返回的items字段包含数据
    total.value = resp.data.data.total     // 假设后端返回的total字段包含总数
  }).catch(e => {
    ElMessage.error('数据加载失败')
  })


}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData()
}

const editObj = (val) => {
  dialogFormVisible.value = true
  currentEditObj.value = Object.assign({}, val)
}

const saveObj = (data) => {
  data.update_username = useUser.userInfo?.username
  if (currentWordType.value === 'txt') {
    editTrain(data).then(resp => {
      // 关闭当前弹窗
      dialogFormVisible.value = false
      // 弹出成功信息
      ElMessage.success('修改成功')
      fetchTableData()
    }).catch(error => {
      ElMessage.error('修改失败')
    })
  } else {
    // 保存前，需要先校验json数据是否符合格式
    let jsonContent = { 'content': data.output }
    validateJsonStr(jsonContent).then(resp => {
      jsonErrorInfo.value = resp.data.data
      jsonValidateStatus.value = resp.data.status
      if (resp.data.status === 200) {
        ElMessageBox.confirm('JSON格式正确，确认修改？', '修改', {
          confirmButtonText: '确定'
        }).then(() => {
          editTrain(data).then(resp => {
            // 关闭当前弹窗
            dialogFormVisible.value = false
            // 弹出成功信息
            ElMessage.success('修改成功')
            fetchTableData()
          }).catch(error => {
            ElMessage.error('修改失败')
          })
        })
      } else {
        ElMessage.error('JSON格式有误')
      }
    })
  }

}

const delObj = (val) => {
  ElMessageBox.confirm('确认删除？', '删除', {
    confirmButtonText: '确定'
  }).then(() => {
    deleteTrainDataset(val, useUser.userInfo?.username).then(resp => {
      ElMessage.success('删除成功')
      fetchTableData()
    }).catch(e => {
      ElMessage.error('删除失败')
    })
  })
}

onMounted(() => {
  fetchTableData()
})
</script>
<style scoped lang='less'>
.upd-btn {
  height: 25px;
  width: 25px;

  &:hover {
    background-color: rgb(153, 145, 100);
    border-radius: 4px;
    // border: 1px solid #f56c6c;
  }
}

.del-btn {
  height: 25px;
  width: 25px;

  &:hover {
    background-color: rgb(116, 74, 66);
    border-radius: 4px;
    // border: 1px solid #f56c6c;
  }
}

.output-label {
  overflow: auto;

  .label-left {
    float: left;
  }

  .label-right {
    float: right;
  }
}

.dialog-foot {
  overflow: auto;

  .dialog-foot-radio {
    float: left;
  }

  .dialog-foot-button {
    float: right;
    margin-right: 20px;
  }
}
</style>